package com.jwater.core.manager.proxy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jwater.io.netty.util.concurrent.DefaultThreadFactory;
import jwater.org.springframework.util.StringUtils;

/**
 * @description:代理进程执行线程池
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class ProxyExecutorUtils {
    protected static Logger logger = LoggerFactory.getLogger(ProxyExecutorUtils.class);

    public static int maxPoolSize;

    public static ExecutorService executorService = null;

    static {
        try {
            String size = System.getProperty("PROXY_MAX_POOL_SIZE");
            if (StringUtils.isEmpty(size)) {
                maxPoolSize = Runtime.getRuntime().availableProcessors() * 2;
                maxPoolSize = maxPoolSize < 16 ? 16 : maxPoolSize;
                maxPoolSize = maxPoolSize > 32 ? 32 : maxPoolSize;
            } else {
                maxPoolSize = Integer.parseInt(size);
            }
            executorService = new ThreadPoolExecutor(1, maxPoolSize, 60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(500), new DefaultThreadFactory("ProxyExecutor"),
                    new CallerRunsPolicy());
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    public static void execute(Runnable command) {
        executorService.execute(command);
    }

    public static void close() {
        executorService.shutdownNow();
    }
}
